class Solution {
public:
    vector<int> sortedSquares(vector<int>& nums) {
        int n = nums.size();
        vector<int> ans(n);
        int i = 0;
        int j = n - 1;
        for (int k = n - 1; k >= 0; --k)
        {
            if (nums[i] * nums[i] > nums[j] * nums[j])
                ans[k] = nums[i] * nums[i++];
            else
                ans[k] = nums[j] * nums[j--];
        }
        return ans;
    }
};